<?php
defined ( 'BASEPATH' ) or exit ( 'No direct script access allowed' );
class Shoppingcart_model extends CI_Model {
	public function __construct() {
		parent::__construct ();
	}
	/*
	 * 根据日期得到购物车的总数量
	 */
	public function count_shoppingcarts_by_date($date){
		if(!empty($date)){
			$this->db->where("DATE_FORMAT(buy_time,'%Y-%m-%d')=",$date);
		}
		$query = $this->db->get('t_shoppingcart');
		return $query->num_rows();
	}
	/*
	 * 根据日期得到购物车的总数量
	 */
	public function count_shoppingcarts_by_date_promoter($date,$promoterid){
		$this->db->join('t_user', 't_shoppingcart.userid = t_user.id','left');
		if(!empty($date)){
			$this->db->where("DATE_FORMAT(buy_time,'%Y-%m-%d')=",$date);
		}
		$this->db->where('promoterid', $promoterid);
		$query = $this->db->get('t_shoppingcart');
		return $query->num_rows();
	}
	/*
	 * 根据日期和分页返回购物车列表
	 */
	public function find_shoppingcarts_by_date($date,$per_page,$offset){
		$this->db->select('t_shoppingcart.id,t_product.name,t_shoppingcart.amount,t_shoppingcart.userid,t_user.contact,t_user.shopname,t_shoppingcart.buy_time');
		$this->db->from('t_shoppingcart');
		$this->db->join('t_product', 't_shoppingcart.productid = t_product.id','left');
		$this->db->join('t_user', 't_shoppingcart.userid = t_user.id','left');
		if(!empty($date)){
			$this->db->where("DATE_FORMAT(buy_time,'%Y-%m-%d')=",$date);
		}
		$this->db->limit($per_page, $offset);
		$this->db->order_by("id", "desc");
		$query = $this->db->get();
		return $query->result_array();
	}
	/*
	 * 根据日期和分页返回购物车列表
	 */
	public function find_shoppingcarts_by_date_promoter($date,$promoterid,$per_page,$offset){
		$this->db->select('t_shoppingcart.id,t_product.name,t_shoppingcart.amount,t_shoppingcart.userid,t_user.contact,t_user.shopname,t_shoppingcart.buy_time');
		$this->db->from('t_shoppingcart');
		$this->db->join('t_product', 't_shoppingcart.productid = t_product.id','left');
		$this->db->join('t_user', 't_shoppingcart.userid = t_user.id','left');
		if(!empty($date)){
			$this->db->where("DATE_FORMAT(buy_time,'%Y-%m-%d')=",$date);
		}
		$this->db->where('promoterid', $promoterid);
		$this->db->limit($per_page, $offset);
		$this->db->order_by("id", "desc");
		$query = $this->db->get();
		return $query->result_array();
	}
	/*
	 * 根据用户ID找到对应的购物车
	 */
	public function find_shoppingcart_by_user($userid){
		$this->db->select('t_shoppingcart.id,t_product.name,t_product.price,t_product.unit,t_shoppingcart.amount');
		$this->db->from('t_shoppingcart');
		$this->db->where('t_shoppingcart.userid',$userid);
		$this->db->join('t_product', 't_shoppingcart.productid = t_product.id','left');
		$query = $this->db->get();
		return $query->result_array();
	}
	/*
	 * 清空购物车
	 */
	public function delete_by_product($productid){
		$this->db->where('productid', $productid);
		$this->db->delete('t_shoppingcart');
		return $this->db->affected_rows()>0;
	}
}